package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.Message;
import com.isunland.managesystem.entity.MessageSuccess;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 新消息
 *
 * @author wangyanan
 */
public class MessageSendFragment extends Fragment {
  protected static final String TAG = MessageSendFragment.class.getSimpleName();
  public static final String EXTRA_MESSAGE = "com.isunland.managesystem.ui.extra_message";
  /** 添加附件 */
  protected static final int REQUEST_EXTRA = ExtraUpLoadDialogFragment.REQUEST_CODE;
  /** 选择人员信息 */
  private static final int REQUEST_CHOOSE_MEMBER = 0;
  /** 查看或编辑 */
  // protected static final int REQUEST_EDIT_OR_SHOW = 2;
  private Callbacks mCallbacks;
  private BaseVolleyActivity mActivity;
  private TextView mTvMember;
  private TextView mTvExtra;
  private EditText mEtContent;
  private ImageView mIvExtra;
  private String mNames = "";
  private String mIds = "";
  private String mContent;
  private Message mMessage;
  private String mFilePath = "";

  //1.保存主表类中定义接口。
  public interface Callbacks {
    void onRefresh();
  }

  @Override public void onAttach(Activity activity) {
    super.onAttach(activity);
    mCallbacks = (Callbacks) activity;
  }

  @Override public void onDetach() {
    super.onDetach();
    mCallbacks = null;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    if (getArguments() != null) {

      mMessage = (Message) getArguments().getSerializable(EXTRA_MESSAGE);
    }
    mActivity = (BaseVolleyActivity) getActivity();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      if (NavUtils.getParentActivityName(getActivity()) != null) {

        ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
      }
    }
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_message_send, container, false);
    findViews(view);
    return view;
  }

  private void findViews(View v) {
    mTvMember = (TextView) v.findViewById(R.id.tv_member_sendMassage);
    RelativeLayout mRlMember = (RelativeLayout) v.findViewById(R.id.rl_member_sendMassage);
    if (mMessage == null) {

      mRlMember.setOnClickListener(new OnClickListener() {

        @Override public void onClick(View v) {
          // Auto-generated method stub
          showDialog(REQUEST_CHOOSE_MEMBER);
        }
      });
    } else {
      mTvMember.setText(mMessage.getReceiverName());
      ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.replyMessage);
    }
    mEtContent = (EditText) v.findViewById(R.id.et_messageContent_sendMassage);
    mTvExtra = (TextView) v.findViewById(R.id.tv_extra_sendMassage);
    mTvExtra.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(REQUEST_EXTRA);
      }
    });
    mIvExtra = (ImageView) v.findViewById(R.id.ib_extra_sendMassage);
    // mIvExtra.setVisibility(View.GONE);
    mIvExtra.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View arg0) {

        showDialog(REQUEST_EXTRA);
      }
    });
  }

  /**
   * 选择文件
   */
  private void chooseFile() {
    /**
     *
     * Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
     * intent.setType("audio/*"); startActivity(Intent.createChooser(intent,
     * "Select music"));
     */
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    startActivityForResult(Intent.createChooser(intent, getString(R.string.chooseFileExplorer)),
        REQUEST_EXTRA);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_confirm, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:

        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }

        return true;
      case R.id.menu_item_confirm:
        mNames = mTvMember.getText().toString().trim();
        if (TextUtils.isEmpty(mNames)) {
          Toast.makeText(getActivity(), R.string.chooseContact, Toast.LENGTH_SHORT).show();
          return true;
        }
        mContent = mEtContent.getText().toString().trim();
        if (TextUtils.isEmpty(mContent)) {
          Toast.makeText(getActivity(), R.string.emptyMessageContent, Toast.LENGTH_SHORT).show();
          return true;
        }
        volleyPost();

        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void volleyPost() {

    MyUtils.showDialogLoading(getActivity());

    if (mMessage == null) {
      String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SEND_MESSAGE);

      HashMap<String, String> params = new HashMap<String, String>();

      params.put("receiverId", mIds);
      params.put("receiverName", mNames);
      params.put("content", mContent);
      params.put("androidPath", mFilePath);
      LogUtil.i(TAG, "url=" + ApiConst.getAbsoluteUrl(ApiConst.URL_SEND_MESSAGE));
      LogUtil.i(TAG, "params=" + params.toString());

      mActivity.volleyPost(url, params, new VolleyResponse() {

        @Override public void onVolleyResponse(String arg0) throws JSONException {

          try {
            MyUtils.dismissDialog();
            LogUtil.i(TAG, "response=" + arg0);
            MessageSuccess mSuccess = new Gson().fromJson(arg0, MessageSuccess.class);
            if (mSuccess == null || mSuccess.getResult() == null) {
              Toast.makeText(getActivity(), R.string.failureSendMessage, Toast.LENGTH_SHORT).show();
              return;
            }
            String successType = mSuccess.getResult();
            if (successType.equalsIgnoreCase("1")) {
              Toast.makeText(getActivity(), R.string.successmessage, Toast.LENGTH_SHORT).show();
              mTvMember.setText("");
              mEtContent.setText("");
              HashMap<String, String> map = new HashMap<String, String>();
              map.put("messageId", mSuccess.getMessageId());
              LogUtil.i(TAG, "messageId=" + mSuccess.getMessageId());
              new FileNetWorkUtil(getActivity()).upLoadFile(mFilePath, ApiConst.URL_MESSAGE_UPLAOD,
                  map, null);
              //2.操作成功后，回调接口。实现跳转
              mCallbacks.onRefresh();
            } else {
              Toast.makeText(getActivity(), R.string.failureSendMessage, Toast.LENGTH_SHORT).show();
            }
          } catch (JsonSyntaxException e) {
            LogUtil.e(TAG, "error=" + e, e);
            Toast.makeText(getActivity(), R.string.failureSendMessage, Toast.LENGTH_SHORT).show();
          }
        }

        @Override public void onVolleyError(VolleyError arg0) {
          // Auto-generated method stub

        }
      });
    } else {
      String url = ApiConst.getAbsoluteUrl(ApiConst.URL_MESSAGE_REPLY);

      HashMap<String, String> params = new HashMap<String, String>();

      params.put("id", mMessage.getId() + "");

      params.put("content", mContent);
      LogUtil.i(TAG, "url=" + ApiConst.getAbsoluteUrl(ApiConst.URL_MESSAGE_REPLY));
      LogUtil.i(TAG, "params=" + params.toString());

      mActivity.volleyPost(url, params, new VolleyResponse() {

        @Override public void onVolleyResponse(String arg0) throws JSONException {

          try {
            MyUtils.dismissDialog();
            LogUtil.i(TAG, "response=" + arg0);
            MessageSuccess mSuccess = new Gson().fromJson(arg0, MessageSuccess.class);
            if (mSuccess == null || mSuccess.getResult() == null) {
              Toast.makeText(getActivity(), R.string.failureSendMessage, Toast.LENGTH_SHORT).show();
              return;
            }
            String successType = mSuccess.getResult();
            if (successType.equalsIgnoreCase("1")) {
              Toast.makeText(getActivity(), R.string.successmessage, Toast.LENGTH_SHORT).show();
              mTvMember.setText("");
              mEtContent.setText("");
              HashMap<String, String> map = new HashMap<String, String>();
              map.put("messageId", mSuccess.getMessageId());
              LogUtil.i(TAG, "messageId=" + mSuccess.getMessageId());
              new FileNetWorkUtil(getActivity()).upLoadFile(mFilePath, ApiConst.URL_MESSAGE_UPLAOD,
                  map, null);
              //2.操作成功后，回调接口。实现跳转
              mCallbacks.onRefresh();
            } else {
              Toast.makeText(getActivity(), R.string.failureSendMessage, Toast.LENGTH_SHORT).show();
            }
          } catch (JsonSyntaxException e) {
            LogUtil.e(TAG, "error=" + e, e);
            Toast.makeText(getActivity(), R.string.failureSendMessage, Toast.LENGTH_SHORT).show();
          }
        }

        @Override public void onVolleyError(VolleyError arg0) {
          // Auto-generated method stub

        }
      });
    }
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog = null;
    switch (requestCode) {
      case REQUEST_CHOOSE_MEMBER:
        dialog = new SendMessageDialogFragment();

        break;
      // case REQUEST_EDIT_OR_SHOW:
      //
      // ExtraReOpenDialogFragment.setFile(mDocPath);
      // dialog =
      // ExtraReOpenDialogFragment.newInstance(R.string.attachmentConfirm,
      // R.string.watch,R.string.clearChoose, R.string.edit);
      // break;
      case REQUEST_EXTRA:
        dialog = ExtraUpLoadDialogFragment.newInstance(mFilePath);
        break;

      default:
        break;
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();

    dialog.setTargetFragment(MessageSendFragment.this, requestCode);
    dialog.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    switch (requestCode) {
      case REQUEST_CHOOSE_MEMBER:

        mNames = data.getStringExtra(SendMessageDialogFragment.EXTRA_NAME);
        mIds = data.getStringExtra(SendMessageDialogFragment.EXTRA_ID);
        mTvMember.setText(mNames);
        break;
      case REQUEST_EXTRA:

        String result = data.getStringExtra(ExtraUpLoadDialogFragment.EXTRA_RESULT);
        if (ExtraUpLoadDialogFragment.VALUE_CLEAR.equalsIgnoreCase(result)) {
          clearExtraFile();
        } else {

          mFilePath = result;
          if (mFilePath != null) {

            String fileName = FileUtil.getFileNameByFilePath(mFilePath);
            //					String[] names =fileName.split("\\.");
            //					String pictureName =names[names.length-2]+"."+names[names.length-1];
            mTvExtra.setText(fileName);
          }
        }

        break;
      // case REQUEST_EDIT_OR_SHOW:
      // if (data != null) {
      //
      // int code = data.getIntExtra(BaseDialogFragment.EXTRA_CHOICE,
      // BaseDialogFragment.VALUE_POSITIVE);
      // if (code == BaseDialogFragment.VALUE_POSITIVE) {// 查看
      //
      // FileUtil.openFile(new File(mDocPath), getActivity());
      //
      // return;
      // }
      //
      // if (code == BaseDialogFragment.VALUE_NAVIGATE) {// 编辑
      // showDialog(REQUEST_EXTRA);
      // return;
      // }
      // if (code == BaseDialogFragment.VALUE_NEUTRAL) {// 清空
      // clearExtraFile();
      // return;
      // }
      //
      // }
      //
      // break;

      default:
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public void clearExtraFile() {
    mFilePath = "";
    mTvExtra.setText("");
  }

  public static Fragment newInstance(Message message) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_MESSAGE, message);
    MessageSendFragment fragment = new MessageSendFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
